<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CaseBak extends Model
{
    protected $table ="c_case_baks";


    /***
     * @param $data
     * @param $case_id
     * 添加记录
     */
    public function add($data, $case_id)
    {
        $info = $this->where([['case_id', '=', $case_id]])->first();
        $allergy = json_decode($data['allergy'], true);
        $diseases_history = json_decode($data['diseases_history'], true);
        if ($info) {
            $this->where([['case_id', '=', $case_id]])->delete();
            if (!empty($allergy)) {
                $allers = [];
                foreach ($allergy as $k => $v) {
                    $allers[$k]['case_id'] = $case_id;
                    $allers[$k]['logs'] = $v;
                    $allers[$k]['created_at'] = date("Y-m-d H:i:s", time());
                    $allers[$k]['updated_at'] = date("Y-m-d H:i:s", time());
                }
                DB::table('c_case_baks')->insert($allers);
            }
            if (!empty($diseases_history)) {
                $allers = [];
                foreach ($diseases_history as $k => $v) {
                    $allers[$k]['case_id'] = $case_id;
                    $allers[$k]['logs'] = $v;
                    $allers[$k]['created_at'] = date("Y-m-d H:i:s", time());
                    $allers[$k]['updated_at'] = date("Y-m-d H:i:s", time());
                }
                DB::table('c_case_baks')->insert($allers);
            }
            return true;
        }
        if (!empty($allergy)) {
            $allers = [];
            foreach ($allergy as $k => $v) {
                $allers[$k]['case_id'] = $case_id;
                $allers[$k]['logs'] = $v;
                $allers[$k]['created_at'] = date("Y-m-d H:i:s", time());
                $allers[$k]['updated_at'] = date("Y-m-d H:i:s", time());
            }
            DB::table('c_case_baks')->insert($allers);
        }
        if (!empty($diseases_history)) {
            $allers = [];
            foreach ($diseases_history as $k => $v) {
                $allers[$k]['case_id'] = $case_id;
                $allers[$k]['logs'] = $v;
                $allers[$k]['created_at'] = date("Y-m-d H:i:s", time());
                $allers[$k]['updated_at'] = date("Y-m-d H:i:s", time());
            }
            DB::table('c_case_baks')->insert($allers);
        }
        return true;
    }
}
